package prog1.helpers;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;

/**
 * Created with IntelliJ IDEA.
 * User: Roi
 * Date: 07/12/13
 *
 * This class builds cipher object according to required parameters, such as algorithm and provider.
 */
public class CipherBuilder {

    private String algorithm;
    private String provider;
    private int mode;
    private Key key;
    private AlgorithmParameterSpec spec;

    /**
     * Adds algorithm to this builder
     * @param algorithm algorithm to use
     * @return self reference
     */
    public CipherBuilder withAlgorithm(String algorithm) {
        this.algorithm = algorithm;
        return this;
    }

    /**
     * Adds provider to this builder
     * @param provider provider to use
     * @return self reference
     */
    public CipherBuilder withProvider(String provider) {
        this.provider = provider;
        return this;
    }

    /**
     * Adds mode to this builder
     * @param mode mode to use
     * @return self reference
     */
    public CipherBuilder withMode(int mode) {
        this.mode = mode;
        return this;
    }

    /**
     * Adds key to this builder
     * @param key key to use
     * @return self reference
     */
    public CipherBuilder withKey(Key key) {
        this.key = key;
        return this;
    }

    /**
     * Adds spec to this builder
     * @param spec spec to use
     * @return self reference
     */
    public CipherBuilder withSpec(AlgorithmParameterSpec spec) {
        this.spec = spec;
        return this;
    }

    /**
     * Builds cipher object from previously set parameters
     * @return cipher object
     * @throws NoSuchPaddingException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     */
    public Cipher build()
            throws NoSuchPaddingException,
            NoSuchAlgorithmException,
            NoSuchProviderException,
            InvalidAlgorithmParameterException,
            InvalidKeyException {
        Cipher cipher = Cipher.getInstance(algorithm, provider);
        cipher.init(mode, key, spec);
        return cipher;
    }
}
